package com.sq.universe.base.interceptor;

import com.sq.universe.base.ann.DataPermissionAnn;
import com.sq.universe.base.constants.BaseConstants;
import com.sq.universe.base.utils.AuthUtils;
import com.sq.universe.base.utils.ReflectUtil;
import com.sq.universe.system.entity.UserEntity;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.web.util.WebUtils;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Properties;

@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        }
)
@Component
public class DataPermissionInterceptor  implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        //由于逻辑关系，只会进入一次
        if(args.length == 4){
            //4 个参数时
            boundSql = ms.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);

        } else {
            //6 个参数时

            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }
        //TODO 自己要进行的各种处理


        //获取路由RoutingStatementHandler
//        RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
//        //获取StatementHandler
//        StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(statementHandler, "delegate");
//        //获取mapper接口
//        MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");
        //获取mapper类文件
        Class<?> clazz = Class.forName(ms.getId().substring(0, ms.getId().lastIndexOf(".")));
        //获取mapper执行方法名
        int length=ms.getId().length();
        String mName = ms.getId().substring(ms.getId().lastIndexOf(".") + 1, length);

        //遍历方法
        for (Method method : clazz.getDeclaredMethods()) {
            //方法是否含有RequiredPermission注解，如果含有注解则将数据结果过滤
            if (method.isAnnotationPresent(DataPermissionAnn.class) && mName.equals(method.getName())) {
                AuthUtils.getCurrentUser();
                DataPermissionAnn requiredPermission =  method.getAnnotation(DataPermissionAnn.class);
                //判断是否为select语句
                if (ms.getSqlCommandType().toString().equals("SELECT")) {
                    String sql = boundSql.getSql();

                }
//                    //将sql注入boundSql
//                    ReflectUtil.setFieldValue(boundSql, "sql", sql);
                break;
            }
        }

        //注：下面的方法可以根据自己的逻辑调用多次，在分页插件中，count 和 page 各调用了一次
        return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
    }




    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
